<template>
  <Card>
    <p slot="title">编辑类型</p>
    <Form
      ref="formDicType"
      :model="formDicType"
      :rules="ruleValidate"
      :label-width="100"
    >
      <Row :gutter="16" type="flex" justify="space-around">
        <i-col span="9">
          <FormItem label="字典类型" prop="dicType">
            <div>
              <InputNumber
                disabled
                style="width: 280px"
                v-model="formDicType.dicType"
                placeholder="请输入字典类型"
              />
            </div>
          </FormItem>
        </i-col>
        <i-col span="9">
          <FormItem label="类型名称" prop="dicTypeName">
            <div>
              <Input
                style="width: 280px"
                v-model.trim="formDicType.dicTypeName"
                placeholder="请输入类型名称"
              />
            </div>
          </FormItem>
        </i-col>
      </Row>
      <Row :gutter="16" type="flex" justify="space-around">
        <i-col span="9">
          <FormItem label="父级名称" prop="dicParentId">
            <div>
              <Input
                v-model="showName"
                placeholder="请选择"
                style="width: 280px"
                :readonly="true"
                @click.native="showOrHideTree"
              />
              <div
                v-show="showTree"
                class="treeShow"
                @mouseover="treeShowToggle(1)"
                @mouseout="treeShowToggle(2)"
              >
                <Tree :data="treeData" @on-select-change="changeCheck" />
              </div>
            </div>
          </FormItem>
        </i-col>
        <i-col span="9"> </i-col>
      </Row>
      <div style="margin: 50px 0 0 45%">
        <Button type="primary" @click="handleSubmit('formDicType')" style="marginRight:20px"
          >提交</Button
        >
        <Button @click="handleReset('formDicType')"
          >取消</Button
        >
      </div>
    </Form>
  </Card>
</template>

<script>
import Util from '@/libs/util.js'
export default {
  name: 'editType',
  data () {
    const validateDicTypeName = (rule, value, callback) => {
      const [url, httpConfig] = [
        '/api/validation/dicTypeName',
        {
          params: { name: value }
        }
      ]
      if (value !== this.dicTypeName) {
        this.$http.get(url, httpConfig).then(response => {
          if (response.data.code === -1) {
            return callback(new Error(response.data.msg))
          } else {
            return callback()
          }
        }).catch(() => {
          return callback(new Error('异步校验出错！'))
        })
      } else {
        return callback()
      }
    }
    return {
      dicTypeName: null,
      treeData: [],
      checkData: [],
      showTree: false,
      show: false,
      formDicType: {
        dicType: null,
        dicTypeName: null,
        dicParentId: null
      },
      ruleValidate: {
        dicType: [
          {
            type: 'number',
            required: true,
            trigger: 'blur'
          }
        ],
        dicTypeName: [
          {
            required: true,
            message: '字典类型不能为空',
            trigger: 'blur'
          },
          {
            required: true,
            max: 50,
            message: '字典类型名称最多50个字符',
            trigger: 'blur'
          },
          { validator: validateDicTypeName, trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    showName () {
      let showName = ''
      for (let i = 0; i < this.checkData.length; i++) {
        if (!showName) {
          if (this.checkData[i] !== undefined) {
            showName = this.checkData[i].title
          }
        } else {
          showName = showName + ',' + this.checkData[i].title
        }
      }
      return showName
    }
  },
  methods: {
    // 重置
    handleReset (name) {
      this.$refs[name].resetFields()
      // this.$router.push({
      //   name: 'paramDic'
      // })
      this.closeMe()
    },
    closeMe () {
      this.$store.commit('app/closePage', {
        vm: this,
        fromName: this.$route.name,
        toName: 'paramDic'
      })
    },
    // 提交
    handleSubmit (name) {
      if (this.formDicType.dicType === this.formDicType.dicParentId) {
        this.$Message.error('父级不能设置为自己！')
      } else {
        this.$refs[name].validate((valid) => {
          if (valid) {
            console.log(this.formDicType, 'type')
            Util.http
              .put('/api/cscpDics/updateType', this.formDicType)
              .then(() => {
                this.$Message.success('提交成功')
                // this.$router.push({
                //   name: 'paramDic'
                // })
                this.closeMe()
              })
          } else {
            // this.$Message.error('提交失败')
            // this.$router.push({
            //   name: 'paramDic'
            // })
            // this.closeMe()
          }
        })
      }
    },

    showOrHideTree () {
      this.showTree = !this.showTree
    },

    treeShowToggle (type) {
      this.showTree = type === 1
    },
    // 添加图标
    setTreeNode (treeData, render) {
      for (let i = 0; i < treeData.length; i++) {
        treeData[i].render = render
        if (treeData[i].children && treeData[i].children.length) {
          this.setTreeNode(treeData[i].children, render)
        }
      }
      return treeData
    },

    render (h, { root, node, data }) {
      return h(
        'span',
        {
          style: {
            display: 'inline-block',
            width: '100%'
          }
        },
        [
          h('span', [
            h('Icon', {
              props: {
                type: 'ios-folder-outline'
              },
              style: {
                marginRight: '8px'
              }
            }),
            h('span', data.title)
          ])
        ]
      )
    },

    init () {
      this.formDicType = JSON.parse(JSON.stringify(this.$byStoreGet('paramDicType')))
      this.dicTypeName = this.formDicType.dicTypeName
      // this.formDicType = JSON.parse(JSON.stringify(this.$route.params.type))
    },
    // 初始化树形结构
    initTree () {
      // let id = this.$route.params.type.dicParentId
      let id = this.$byStoreGet('paramDicType').dicParentId
      let self = this
      if (id) {
        Util.http.get(`/api/cscpDics/getTreeExpand/${id}`).then((res) => {
          this.treeData = this.setTreeNode(res.data, self.render)
          this.checkData = [{ title: this.$byStoreGet('paramDicType').parentIdName }]
        })
      } else {
        Util.http.get('/api/cscpDics/getTree').then((res) => {
          this.treeData = this.setTreeNode(res.data, self.render)
        })
      }
    },
    // 选择树数据
    changeCheck (data) {
      this.checkData = data
      if (data.length === 1) {
        this.formDicType.dicParentId = data[0].dicType
      // this.showTree = false
      } else {
        this.formDicType.dicParentId = null
      }
    }
  },
  mounted () {
    this.initTree()
    this.init()
  }
}
</script>

<style lang="less" scoped>
.treeShow {
  position: absolute;
  z-index: 9999;
  max-height: 300px;
  overflow: auto;
  width: 280px;
  background-color: #fff;
  box-sizing: border-box;
  border-radius: 4px;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.2);
}
</style>
